package com.charlotte.study.gupao.delegate.mvc;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author junjie.ding
 * @date 2020/3/13
 */
public class DispatcherServlet extends HttpServlet {

    private Map<String, Method> handlerMapping = new HashMap<>();

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doDispatcher(req, res);
    }

    private void doDispatcher(HttpServletRequest req, HttpServletResponse res) {
        String uri = req.getRequestURI();

        try {
            handlerMapping.get(uri).invoke(null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void init() throws ServletException {
        try {
            handlerMapping.put("/url.json", MemberController.class.getMethod("index", null));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
